import { request } from "./utils"

type Task = {
  status: string
  dueAt: string
  createdBy: {
    workspaceMemberId: string
  }
}

export const summariseTaskCreation = async (date: string) => {
  const { tasks }: { tasks: Task[] } = await request(
    `tasks?filter=createdAt[gte]:${date}`,
  )
  if (tasks.length === 0) {
    return '- No Tasks were added'
  }

  const presentDateISOString = new Date().toISOString()
  const workspaceMemberIdsDueDateCounter: Record<string, number> = {}
  let workspaceMembers = []

  tasks.forEach((task) => {
    if (task.status === 'DONE') {
      return
    }

    if (presentDateISOString >= task.dueAt) {
      if (!workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId]) {
        workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId] = 0
      }

      workspaceMemberIdsDueDateCounter[task.createdBy.workspaceMemberId] += 1
    }
  })

  for (const { userId, count } of findMaxIncompleteKeys(workspaceMemberIdsDueDateCounter)) {
    const data = await request(`workspaceMembers/${userId}`)
    if (data.workspaceMember) {
      workspaceMembers.push({
        ...data.workspaceMember,
        slackCount: count
      })
    }
  }

  let slackerMessage = workspaceMembers.length > 0 ? workspaceMembers.reduce((text, member, index) => {
    if (index === 0 && workspaceMembers.length === 1) {
      return `${member.name.firstName} slacked the most with ${member.slackCount} Tasks overdue`
    }

    if (index !== workspaceMembers.length - 1) {
      return text.concat(`, ${member.name.firstName}`)
    }

    if (index === workspaceMembers.length - 1) {
      return text.concat(`, and ${member.name.firstName} slacked the most with ${member.slackCount} Tasks overdue`)
    }
  }, '') : 'No one was caught slacking!'

  const tasksCompletedOnTime = tasks.filter(
    task => task.status === 'DONE' && task.dueAt >= presentDateISOString
  )

  const taskCompletionPercentage = tasksCompletedOnTime.length > 0
    ? (tasksCompletedOnTime.length / tasks.length) * 100
    : NaN

  const taskCompletionMessage = isNaN(taskCompletionPercentage)
    ? 'No completed Tasks yet'
    : `${taskCompletionPercentage.toFixed(2)}% of Tasks were completed on time`

  return `- ${tasks.length} Tasks were created
- ${taskCompletionMessage}
- ${slackerMessage}`
}

/**
 * @description This is generated by AI
 */
const findMaxIncompleteKeys = (workspaceMemberIdsDueDateCounter: Record<string,number>) => {
  // Get the maximum incomplete count
  const max = Math.max(...Object.values(workspaceMemberIdsDueDateCounter));

  // Filter keys that match the maximum value
  return Object.entries(workspaceMemberIdsDueDateCounter)
    .filter(([_, count]) => count === max)
    .map(([userId, count]) => ({ userId, count }))
};
